package com.yc.edu.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用Python脚本执行工具类
 */
@Component
@ConfigurationProperties(prefix = "pythonexe")
public class PythonUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PythonUtil.class);

    private static String pathAudio;

    private static String pathVideo;

    private static String videoPath;

    private static String videoworkPath;

    private static String virtualEnv;

    /**
     * 执行Python脚本
     *
     * @param pythonExecutable python可执行文件路径
     * @param scriptPath       脚本路径
     * @param args             脚本参数
     * @return 脚本输出结果列表
     */
    public static List<String> executePythonScript(String pythonExecutable, String env, String scriptPath, String... args) {
        List<String> result = new ArrayList<>();

        ProcessBuilder pb = new ProcessBuilder(getCommand(pythonExecutable, scriptPath, args));
        if (env != null && !env.equals("")) {
            pb.directory(new File(env));
        }
        pb.redirectErrorStream(true);

        try {
            Process process = pb.start();

            // 解决输出中文乱码问题
            BufferedInputStream bis = new BufferedInputStream(process.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(bis, "GBK"));

            String line;
            int flag = 0;

            while ((line = reader.readLine()) != null) {
                LOGGER.info(line);
                result.add(line);
                if (line.contains("The generated video is named")) flag += 1;
                if (flag == 1) {
                    result.clear();
                    String respath = FilePathProcessor(line);
                    result.add(respath);
                    process.destroy();
                    return result;
                }

            }

            process.waitFor();
            bis.close();
            reader.close();
        } catch (Exception e) {
            LOGGER.error("执行Python脚本出错：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取Python脚本执行命令
     *
     * @param pythonExecutable python可执行文件路径
     * @param scriptPath       脚本路径
     * @param args             脚本参数
     * @return 执行命令列表
     */
    private static List<String> getCommand(String pythonExecutable, String scriptPath, String[] args) {
        List<String> command = new ArrayList<>();
        command.add(pythonExecutable);
        command.add(scriptPath);
        for (String arg : args) {
            command.add(arg);
        }
        return command;
    }

    public static String getPathAudio() {
        return pathAudio;
    }

    public void setPathAudio(String pathAudio) {
        PythonUtil.pathAudio = pathAudio;
    }

    public static String getPathVideo() {
        return pathVideo;
    }

    public void setPathVideo(String pathVideo) {
        PythonUtil.pathVideo = pathVideo;
    }

    public static String getVideoPath() {
        return videoPath;
    }

    public void setVideoPath(String videoPath) {
        PythonUtil.videoPath = videoPath;
    }

    public static String getVideoworkPath() {
        return videoworkPath;
    }

    public void setVideoworkPath(String videoworkPath) {
        PythonUtil.videoworkPath = videoworkPath;
    }

    public static String getVirtualEnv() {
        return virtualEnv;
    }

    public void setVirtualEnv(String virtualEnv) {
        PythonUtil.virtualEnv = virtualEnv;
    }

    public static String FilePathProcessor(String line) {
        String[] parts = line.split(" ");
        String fileName = parts[parts.length - 3];

        //  返回绝对路径 String directory =parts[parts.length-1];
        String directory = line.substring(line.lastIndexOf('\\') + 1, line.length());
        return directory + "\\" + fileName;
    }
}
